import { Prisma } from '@prisma/client';
import prisma from '@/server/lib/prisma';
import { RoleSchema } from '@/server/lib/zodSchema';
import { array } from 'zod';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    RoleSchema.parse(body); // 校验参数

    // 角色名称和权限字符是否已存在
    const isRoleKey = await prisma.sys_role.findFirst({
      where: {
        roleKey: body.roleKey
      }
    })
    if (isRoleKey) {
      return {
        code: 400,
        msg: '权限字符已存在',
      }
    }

    const isRoleName = await prisma.sys_role.findFirst({
      where: {
        roleName: body.roleName
      }
    })
    if (isRoleName) {
      return {
        code: 400,
        msg: '角色名称已存在',
      }
    }

    // 参数
    const menuCreate: any = [];
    if (body.menus && Array.isArray(body.menus)) {
      body.menus.forEach((menuId: any) => {
        menuCreate.push({
          menuId: menuId,
        })
      })
    }
    const data: Prisma.sys_roleCreateInput = {
      roleName: body.roleName as string,
      roleKey: body.roleKey,
      roleSort: Number(body.roleSort || 0),
      status: body.status,
      remark: body.remark,
      menus: {
        create: menuCreate,
      }
    }
    const result = await prisma.sys_role.create({
      data,
    });
    return {
      code: 200,
      data: result,
      msg: '创建成功'
    }
  } catch (error: any) {
    const err = JSON.parse(error);
    return {
      code: 400,
      msg: err[0].message || '未知错误',
    }
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})
